//
//  DBOauthController.swift
//  大波微博swift
//
//  Created by 大波 on 16/2/28.
//  Copyright © 2016年 zhaojin. All rights reserved.
//

import UIKit
import SVProgressHUD

class DBOauthController: UIViewController {
    
    override func loadView() {
        
        //在loadView方法里面设置可以不用约束  直接就是全屏
        view = webView
        
        webView.delegate = self
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        setNavigationItem()
        
        webViewLoadRequest()
    }
    
    ///webView加载请求
    func webViewLoadRequest() {
        
        let requestURL = DBNetworkTool.shareNetworkTool.oauthLoginURL()
        
        let request = NSURLRequest.init(URL: requestURL)
        
        webView.loadRequest(request)
    }
    
    ///设置导航栏按钮
    func setNavigationItem() {
        
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "填充", style: UIBarButtonItemStyle.Plain, target: self, action: "writeFill")
        
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.Plain, target: self, action: "close")
    }
    
    func writeFill() {
        
        //        print(__FUNCTION__)
        //        let js = "document.getElementById('userId').value='13432020457';document.getElementById('passwd').value='81726278abc'"
        //
        //        webView.stringByEvaluatingJavaScriptFromString(js)
        
        let accountJS = "document.getElementById('userId').value='13432020457';"
        
        let pwdJS = "document.getElementById('passwd').value='81726278abc'"
        
        webView.stringByEvaluatingJavaScriptFromString(accountJS)
        
        webView.stringByEvaluatingJavaScriptFromString(pwdJS)
    }
    
    func close() {
        
        SVProgressHUD.dismiss()
        
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    //MARK: - 懒加载
    let webView: UIWebView = UIWebView()
}

//MARK: - UIWebViewDelegate 代理方法
extension DBOauthController: UIWebViewDelegate {
    
    ///webView开始加载
    func webViewDidStartLoad(webView: UIWebView) {
        
        SVProgressHUD.showWithStatus("正在努力加载中!!!~~~,客官稍等片刻!!!~~~", maskType: SVProgressHUDMaskType.Gradient)
    }
    
    ///webView加载完成
    func webViewDidFinishLoad(webView: UIWebView) {
        
        SVProgressHUD.showSuccessWithStatus("加载成功!!!", maskType: SVProgressHUDMaskType.Gradient)
    }
    
    ///webView加载失败
    func webView(webView: UIWebView, didFailLoadWithError error: NSError?) {
        
        //        print("error \(error)")
        
        SVProgressHUD.dismiss()
        
        if error?.code != 102 {
            
            SVProgressHUD.showErrorWithStatus("哎哟!~您的网络不行了!!!~~", maskType: SVProgressHUDMaskType.Black)
        }
    }
    
    ///webView询问我们是否要加载某个请求  true  加载   false  不加载
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        let URLString = request.URL!.absoluteString
        
        //        print("URLString: \(URLString)")
        
        /*
        //点击授权按钮后的URL
        URLString: http://www.baidu.com/?code=51e007339b9596da11e1aec5d609e5d8
        
        //点击取消按钮后的URL
        URLString: http://www.baidu.com/?error_uri=%2Foauth2%2Fauthorize&error=access_denied&error_description=user%20denied%20your%20request.&error_code=21330
        */
        
        //判断所有的网络请求是否是授权界面的两个按钮点击请求
        if URLString.hasPrefix(DBNetworkTool.shareNetworkTool.redirect_uri) {
            
            ///获取问号  参数分隔符后面的字符串
            let query = request.URL!.query! as NSString
            
            //截取参数
            let code = "code="
            
            //判断授权按钮与取消按钮
            if query.hasPrefix(code) {
                
                //获取code
                let codeString = query.substringFromIndex(code.characters.count)
                
                //把数据移到viewModel处理
                DBUserAccountViewModel.shareUserAccountViewModel.loadAccessToken(codeString) {
                    
                    (error: NSError?) -> () in
                    
                    //判断点击了授权按钮后获取token有没获取成功
                    if error != nil {
                        
                        SVProgressHUD.showErrorWithStatus("授权获取失败")
                        
                        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (Int64)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), { () -> Void in
                            
                            //点击授权按钮失败关闭控制器
                            self.close()
                        })
                        
                        return
                    }
                 
                    //账户保存成功
                    self.close()
                    
                    AppDelegate.outSwitchMain(false)
                }
                
            } else {
                
                //用户点击取消后关闭控制器
                close()
            }
            
            //点击了取消或者授权按钮  webView不加载请求
            return false
        }
        
        //不是点击授权界面的取消或者是授权按钮  webView加载请求
        return true
    }
}




/*
URLString: https://api.weibo.com/oauth2/authorize?client_id=13532587&redirect_uri=http://www.baidu.com/#
URLString: https://api.weibo.com/oauth2/authorize
URLString: http://www.baidu.com/?code=51e007339b9596da11e1aec5d609e5d8
URLString: https://m.baidu.com/?code=51e007339b9596da11e1aec5d609e5d8&from=844b&vit=fps


URLString: https://api.weibo.com/oauth2/authorize?client_id=13532587&redirect_uri=http://www.baidu.com/
URLString: https://api.weibo.com/oauth2/authorize?client_id=13532587&redirect_uri=http://www.baidu.com/#
URLString: https://api.weibo.com/oauth2/authorize
URLString: http://www.baidu.com/?error_uri=%2Foauth2%2Fauthorize&error=access_denied&error_description=user%20denied%20your%20request.&error_code=21330
URLString: https://m.baidu.com/?error_uri=%2Foauth2%2Fauthorize&error=access_denied&error_description=user%20denied%20your%20request.&error_code=21330&from=844b&vit=fps


//点击授权按钮后的URL
URLString: http://www.baidu.com/?code=51e007339b9596da11e1aec5d609e5d8

//点击取消按钮后的URL
URLString: http://www.baidu.com/?error_uri=%2Foauth2%2Fauthorize&error=access_denied&error_description=user%20denied%20your%20request.&error_code=21330
*/




















